from flask import Blueprint, request, jsonify
from toutiao.model.db_routing import db
from toutiao.model.db_routing import Channel, UserChannel

channel_api = Blueprint('channel', __name__, url_prefix='/channel')
user_channel_api = Blueprint('user-channel', __name__, url_prefix='/user-channel')


@channel_api.route('/add', methods=['GET'])
def channel_add():
    """
    添加频道
    :return:
    """
    args = request.json
    name = args.get('name')
    sequence = args.get('sequence')
    is_visible = args.get('is_visible')
    is_default = args.get('is_default')
    if not all([name, sequence, is_visible, is_default]):
        return jsonify({'name': 20001, 'msg': '参数不全'})
    channel = Channel(name=name, sequence=sequence, is_visible=is_visible, is_default=is_default)
    db.session.add(channel)
    db.session.commit()
    return jsonify({'name': 20000, 'msg': '添加成功'})


@channel_api.route('/delete', methods=['POST'])
def channel_delete():
    """
    删除接口
    :return:
    """
    channel_info = Channel.query.get(id)
    if not channel_info:
        return jsonify({"name": 20001, 'msg': '该数据不存在'})
    Channel.query.filter(Channel.id == id).delete()
    db.session.commit()
    return jsonify({'name': 20000, 'msg': '删除成功'})


@user_channel_api.route('/add_u_channel', methods=['POST'])
def add_u_channel():
    """
    用户关注频道
    :return:
    """
    args = request.json
    user_id = args.get('user_id')
    channel_id = args.get('channel_id')
    if not all([user_id, channel_id]):
        return jsonify({'name': user_id, 'msg': '参数不安'})
    u_channel = Channel(user_id=user_id, channel_id=channel_id)
    db.session.add(u_channel)
    db.session.commit()
    return jsonify({'name': 20000, 'msg': '添加成功>'})


@user_channel_api.route('u_delete', methods=['DELETE'])
def add_d_delete():
    """
    用户取消关注频道
    :return:
    """
    u_chan_info = UserChannel.query.get(id)
    if not u_chan_info:
        return jsonify({"name": 20001, 'msg': '该数据不存在'})
    UserChannel.query.filter(UserChannel.id == id).delete()
    db.session.commit()
    return jsonify({'name': 20000, 'msg': '>'})
